package com.cci.kangdao.escalation.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.common.RedisKeys;
import com.cci.kangdao.crmapi.CRMHttpClientUtil;
import com.cci.kangdao.crmapi.CRMServiceApiImpl;
import com.cci.kangdao.crmapi.CRMServiceConst;
import com.cci.kangdao.dao.LoginDao;
import com.cci.kangdao.dao.UserTDao;
import com.cci.kangdao.dao.WorkOrderTDao;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dto.PagedRequest;
import com.cci.kangdao.dto.PagedResponse;
import com.cci.kangdao.escalation.aop.model.EscalationThreadLocal;
import com.cci.kangdao.escalation.dao.*;
import com.cci.kangdao.escalation.dto.request.GetEscalationOrderListRequest;
import com.cci.kangdao.escalation.dto.request.GetWorkOrderListRequest;
import com.cci.kangdao.escalation.dto.request.SubmitReasonRequest;
import com.cci.kangdao.escalation.dto.request.SubmitSolutionRequest;
import com.cci.kangdao.escalation.dto.response.*;
import com.cci.kangdao.escalation.model.*;
import com.cci.kangdao.escalation.model.type.FormStatusType;
import com.cci.kangdao.escalation.model.type.FormType;
import com.cci.kangdao.escalation.model.type.RoleType;
import com.cci.kangdao.escalation.model.type.TypeDictionary;
import com.cci.kangdao.escalation.service.EscalationService;
import com.cci.kangdao.exception.CommonException;
import com.cci.kangdao.exception.ExceptionStatus;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.NotifyConfigService;
import com.cci.kangdao.service.impl.SMSEnum;
import com.cci.kangdao.utilTool.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class EscalationServiceImpl implements EscalationService {

    @Resource
    private EscalationReasonTDao escalationReasonTDao;

    @Resource
    private WorkOrderTDao workOrderTDao;

    @Resource
    private EscalationOrderTDao escalationOrderTDao;

    @Resource
    private EscalationFlowTDao escalationFlowTDao;

    @Resource
    private EscalationPrincipalTDao escalationPrincipalTDao;

    @Resource
    private LoginDao loginDao;

    @Resource
    private EscalationSolutionTDao escalationSolutionTDao;

    @Resource
    private RedisClientUtils redisClientUtils;

    @Resource
    private PositionExpertTDao positionExpertTDao;

    @Resource
    private EscalationReasonSupplementTMapper reasonSupplementTMapper;
    @Resource
    private UserTDao userTDao;
    @Resource
    private NotifyConfigService notifyConfigService;

    private org.apache.log4j.Logger log = Logger.getLogger(this.getClass().getName());

    @Override
    public void submitEscalation(SubmitReasonRequest request) throws Exception {
        //Type  1：技师创建工单；2：工程师升级工单；3：区域工程师创建工单；4：技师再升级；6：技师不同意专家反馈，继续待服务专家反馈
        HttpServletResponse response = RequestContextHolder.getResponse();
        if (request.getType() != null && request.getReasonKey() != null && request.getReasonValue() != null) {
            String typeStr1 = "1,3";
            String typeStr2 = "2,4,6";
            if (typeStr1.contains(request.getType()) && null == request.getWorkOrderId()) {
                ParameterTool.writeResponse(response, SMSEnum.type17.getIndex(), SMSEnum.type17.getName());
                return;
            }
            if (typeStr2.contains(request.getType()) && null == request.getEscalationOrderId()) {
                ParameterTool.writeResponse(response, SMSEnum.type17.getIndex(), SMSEnum.type17.getName());
                return;
            }
            UserT userT = UserThreadLocal.get();
            String type = request.getType();
            //判断是否有对应的负责人
            int con = 0;
            if (typeStr1.contains(type)) {
                con = isPrincipalExisted(type, request.getReasonKey(), userT, request.getWorkOrderId());  // -1 区域工程师不存在； -2 专家不存在
            } else if ("2".contains(type)) {
                con = isPrincipalExisted(type, request.getReasonKey(), userT, request.getEscalationOrderId());
            } else if ("4".contains(type)) {
                EscalationPrincipalT escalationPrincipalT = escalationPrincipalTDao.selectByOrderId(request.getEscalationOrderId());
                con = isPrincipalExisted(type, request.getReasonKey(), loginDao.getUserByid(String.valueOf(escalationPrincipalT.getPrincipalId())), request.getEscalationOrderId());
            } else if ("6".contains(type)) {
                con = isPrincipalExisted(type, request.getReasonKey(), userT, request.getEscalationOrderId());
            }
            if (con == -1) {
                ParameterTool.writeErrorResponse(response, -26);
                return;
            } else if (con == -2) {
                ParameterTool.writeErrorResponse(response, -27);
                return;
            }
            try {
                // 加锁处理，避免多次升级
                if (!redisClientUtils.lock("escalationOrder-" + (null == request.getWorkOrderId() ? request.getEscalationOrderId() : request.getEscalationOrderId()), 60L)) {
                    ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -98);
                    return;
                }
                //主动升级同步给SF对象
                SynSfParam synSfParam = new SynSfParam();

                //主动升级同步给SF添加公共数据
                synSfParam.setUpgradeReasonType(request.getReasonValue());
                synSfParam.setUpgradeReasonDescription(request.getSupplementReason());
                synSfParam.setUpgradeFormStatus(FormStatusType.PROCESSING.getMessage());
                synSfParam.setUpgradeSubmitUserName(userT.getContact());
                synSfParam.setUpgradeSubmitUserPhone(userT.getPhone());
                String nowTime = LocalTimeUtil.getRealCurrentTime();
                synSfParam.setUpgradeSubmitDateTime(nowTime);
                //1：技师创建工单；3：区域工程师创建工单；
                if ("1".equals(type) || "3".equals(type)) {
                    //查询工单
                    Map<String, Object> orderInfoMap = workOrderTDao.getOrderById(request.getWorkOrderId());
                    synSfParam.setWorkOrderNo(orderInfoMap.get("OrderNo") + "");
                    synSfParam.setUpgradeDescription(orderInfoMap.get("CustomerComplaint") + "");
                    synSfParam.setUpgradeCreatedDateTime(nowTime);
                    //同步给SF表单类型
                    synSfParam.setUpgradeFormType(FormType.NORMAL_UPGRADE.getMessage());
                    //表单处理人角色
                    if ("1".equals(type)) {
                        synSfParam.setUpgradeStage(RoleType.REGIONAL_ENGINEER.getMessage());
                        //区域工程师姓名
                        UserT engineerUserT = workOrderTDao.getFieldEngineerByWorkOrderId(request.getWorkOrderId());
                        if(null != engineerUserT){
                            synSfParam.setUpgradeStageName(engineerUserT.getContact());
                        }
                    } else if ("3".equals(type)) {
                        synSfParam.setUpgradeStage(RoleType.SERVICE_EXPERT.getMessage());
                        //服务专家姓名
                        UserT expertsUserT = escalationOrderTDao.getExpertsByWorkOrderId(request.getWorkOrderId(),Integer.valueOf(request.getReasonKey()));
                        if(null == expertsUserT){
                            expertsUserT = escalationOrderTDao.getExpertsByAll();
                        }
                        if(null != expertsUserT){
                            synSfParam.setUpgradeStageName(expertsUserT.getContact());
                            synSfParam.setExpertsName(expertsUserT.getContact());
                        }
                    }
                    // 创建升级工单逻辑
                    //判断是否已经升级
                    if (!getValidationByOrderId(request)) {
                        ParameterTool.writeErrorResponse(response, -20);
                        return;
                    }
                    //新增：主动升级单表
                    long conOrder = insertEscalationOrderT(request, userT, synSfParam);
                    if (conOrder < 1) {
                        throw new RuntimeException();
                    }

                    EscalationThreadLocal.set(conOrder);
                    request.setEscalationOrderId(conOrder);
                    //新增：负责人表：技师创建直接匹配工程师；区域工程师创建则将本人设置为负责人
                    int conPrincipal = insertEscalationPrincipal(request.getType(), request.getEscalationOrderId(), request.getWorkOrderId(), userT);
                    if (conPrincipal == 0) {
                        throw new RuntimeException();
                    }
                    //新增：升级单原因表
                    int conReason = insertEscalationReasonT(request, userT, synSfParam);
                    if (conReason < 1) {
                        throw new RuntimeException();
                    }
                    //新增：流水表
                    int conFlow;
                    if ("1".equals(type)) {
                        conFlow = insertEscalationFlowT(request.getEscalationOrderId(), TypeDictionary.FLOWTYPE_TECHNICIAN_TO_FIELDENGINEER.getCode(), TypeDictionary.ORDERTYPE_FIELDENGINEER_FEEDBACK.getCode(), userT,synSfParam.getExpertsName());
                    } else {
                        conFlow = insertEscalationFlowT(request.getEscalationOrderId(), TypeDictionary.FLOWTYPE_FIELDENGINEER_TO_SERVICEEXPERT_CREAT.getCode(), TypeDictionary.ORDERTYPE_SERVICEEXPERT_FEEDBACK.getCode(), userT,synSfParam.getExpertsName());
                    }
                    if (conFlow < 1) {
                        throw new RuntimeException();
                    }
                } else if ("2".equals(type)) {//2：工程师升级工单
                    // 工程师升级工单逻辑
                    // 判断是否已完成升级，状态为1，代表新工单，且未升级，未处理
                    if (!getValidationByOrderId(request)) {
                        ParameterTool.writeErrorResponse(response, -21);
                        return;
                    }
                    EscalationThreadLocal.set(request.getEscalationOrderId());
                    // 更改主动升级单表
                    EscalationOrderT escalationOrderT = escalationOrderTDao.selectByPrimaryKey(request.getEscalationOrderId());
                    String time = LocalTimeUtil.getRealCurrentTime();
                    //查询工单
                    Map<String, Object> orderInfoMap = workOrderTDao.getOrderById(escalationOrderT.getWorkOrderId());
                    synSfParam.setWorkOrderNo(orderInfoMap.get("OrderNo") + "");
                    synSfParam.setUpgradeDescription(orderInfoMap.get("CustomerComplaint") + "");
                    synSfParam.setUpgradeAppNo(escalationOrderT.getOrderNo());
                    //同步给SF表单类型
                    synSfParam.setUpgradeFormType(FormType.NORMAL_UPGRADE.getMessage());
                    //同步给SF表单提交人角色
                    synSfParam.setUpgradeSubmitUser(RoleType.REGIONAL_ENGINEER.getMessage());
                    synSfParam.setUpgradeStage(RoleType.SERVICE_EXPERT.getMessage());
                    //服务专家姓名
                    UserT expertsUserT = escalationOrderTDao.getExpertsByWorkOrderId(request.getWorkOrderId(),Integer.valueOf(request.getReasonKey()));
                    if(null == expertsUserT){
                        expertsUserT = escalationOrderTDao.getExpertsByAll();
                    }
                    if(null != expertsUserT){
                        synSfParam.setUpgradeStageName(expertsUserT.getContact());
                        synSfParam.setExpertsName(expertsUserT.getContact());
                    }
                    escalationOrderT.setUpdator(userT.getId());
                    escalationOrderT.setUpdateTime(time);
                    escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_SERVICEEXPERT_FEEDBACK.getCode());
                    int conUpdateOrder = escalationOrderTDao.updateByPrimaryKey(escalationOrderT);
                    if (conUpdateOrder < 1) {
                        throw new RuntimeException();
                    }
                    //新增：升级单原因表
                    int conReason = insertEscalationReasonT(request, userT, synSfParam);
                    if (conReason < 1) {
                        throw new RuntimeException();
                    }
                    //新增：负责人表
                    int conPrincipal = insertEscalationPrincipal(request.getType(), request.getEscalationOrderId(), null, userT);
                    if (conPrincipal < 1) {
                        throw new RuntimeException();
                    }
                    //新增：流水表
                    int conFlow = insertEscalationFlowT(request.getEscalationOrderId(),
                            TypeDictionary.FLOWTYPE_FIELDENGINEER_TO_SERVICEEXPERT.getCode(),
                            TypeDictionary.ORDERTYPE_SERVICEEXPERT_FEEDBACK.getCode(), userT,synSfParam.getExpertsName());
                    if (conFlow < 1) {
                        throw new RuntimeException();
                    }
                } else if ("4".equals(type)) {//4：技师再升级；
                    // 再升级
                    if (!getValidationByOrderId(request)) {
                        ParameterTool.writeErrorResponse(response, -21);
                        return;
                    }
                    // 更改主动升级单表
                    String time = LocalTimeUtil.getRealCurrentTime();
                    EscalationThreadLocal.set(request.getEscalationOrderId());
                    EscalationOrderT escalationOrderT = escalationOrderTDao.selectByPrimaryKey(request.getEscalationOrderId());
                    escalationOrderT.setUpdator(userT.getId());
                    escalationOrderT.setUpdateTime(time);
                    escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_SERVICEEXPERT_FEEDBACK.getCode());

                    Map<String, Object> orderInfoMap = workOrderTDao.getOrderById(escalationOrderT.getWorkOrderId());
                    synSfParam.setWorkOrderNo(orderInfoMap.get("OrderNo") + "");
                    synSfParam.setUpgradeDescription(orderInfoMap.get("CustomerComplaint") + "");
                    synSfParam.setUpgradeAppNo(escalationOrderT.getOrderNo());
                    //同步给SF表单类型
                    synSfParam.setUpgradeFormType(FormType.RE_UPGRADE.getMessage());
                    //同步给SF表单提交人角色
                    synSfParam.setUpgradeSubmitUser(RoleType.SERVICE_TECHNICIAN.getMessage());
                    synSfParam.setUpgradeStage(RoleType.SERVICE_EXPERT.getMessage());
                    //服务专家姓名
                    UserT expertsUserT = escalationOrderTDao.getExpertsByWorkOrderId(request.getWorkOrderId(),Integer.valueOf(request.getReasonKey()));
                    if(null == expertsUserT){
                        expertsUserT = escalationOrderTDao.getExpertsByAll();
                    }
                    if(null != expertsUserT){
                        synSfParam.setUpgradeStageName(expertsUserT.getContact());
                        synSfParam.setExpertsName(expertsUserT.getContact());
                    }
                    int conUpdateOrder = escalationOrderTDao.updateByPrimaryKey(escalationOrderT);
                    if (conUpdateOrder < 1) {
                        throw new RuntimeException();
                    }
                    //新增：升级单原因表
                    int conReason = insertEscalationReasonT(request, userT, synSfParam);
                    if (conReason < 1) {
                        throw new RuntimeException();
                    }
                    //新增：负责人表
                    int conPrincipal = insertEscalationPrincipal(request.getType(), request.getEscalationOrderId(), null, userT);
                    if (conPrincipal < 1) {
                        throw new RuntimeException();
                    }
                    // 新增：流水表
                    int conFlow = insertEscalationFlowT(request.getEscalationOrderId(),
                            TypeDictionary.FLOWTYPE_TECHNICIAN_TO_SERVICEEXPERT.getCode(),
                            TypeDictionary.ORDERTYPE_SERVICEEXPERT_FEEDBACK.getCode(),
                            userT,synSfParam.getExpertsName());
                    if (conFlow < 1) {
                        throw new RuntimeException();
                    }

                } else if ("6".equals(type)) {// 技师不同意专家的反馈，继续升级:待服务专家反馈
                    //更换内部type值
//                    request.setType("6");
                    if (!getValidationByOrderId(request)) {
                        ParameterTool.writeErrorResponse(response, -21);
                        return;
                    }
                    String time = LocalTimeUtil.getRealCurrentTime();

                    // 更改主动升级单表
                    EscalationThreadLocal.set(request.getEscalationOrderId());
                    EscalationOrderT escalationOrderT = escalationOrderTDao.selectByPrimaryKey(request.getEscalationOrderId());
                    escalationOrderT.setUpdator(userT.getId());
                    escalationOrderT.setUpdateTime(time);
                    escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_SERVICEEXPERT_FEEDBACK.getCode());

                    Map<String, Object> orderInfoMap = workOrderTDao.getOrderById(escalationOrderT.getWorkOrderId());
                    synSfParam.setWorkOrderNo(orderInfoMap.get("OrderNo") + "");
                    synSfParam.setUpgradeDescription(orderInfoMap.get("CustomerComplaint") + "");
                    synSfParam.setUpgradeAppNo(escalationOrderT.getOrderNo());
                     //同步给SF表单类型
                    synSfParam.setUpgradeFormType(FormType.RE_UPGRADE.getMessage());
                    //同步给SF表单提交人角色
                    synSfParam.setUpgradeSubmitUser(RoleType.SERVICE_TECHNICIAN.getMessage());
                    synSfParam.setUpgradeStage(RoleType.SERVICE_EXPERT.getMessage());
                    //服务专家姓名
                    UserT expertsUserT = escalationOrderTDao.getExpertsByWorkOrderId(request.getWorkOrderId(),Integer.valueOf(request.getReasonKey()));
                    if(null == expertsUserT){
                        expertsUserT = escalationOrderTDao.getExpertsByAll();
                    }
                    if(null != expertsUserT){
                        synSfParam.setUpgradeStageName(expertsUserT.getContact());
                        synSfParam.setExpertsName(expertsUserT.getContact());
                    }
                    int conUpdateOrder = escalationOrderTDao.updateByPrimaryKey(escalationOrderT);
                    if (conUpdateOrder < 1) {
                        throw new RuntimeException();
                    }
                    //新增：升级单原因表
                    int conReason = insertEscalationReasonT(request, userT, synSfParam);
                    if (conReason < 1) {
                        throw new RuntimeException();
                    }
                    //新增：负责人表
                    int conPrincipal = insertEscalationPrincipal("8", request.getEscalationOrderId(), null, userT);
                    if (conPrincipal < 1) {
                        throw new RuntimeException();
                    }
                    // 新增：流水表
                    int conFlow = insertEscalationFlowT(request.getEscalationOrderId(),
                            TypeDictionary.FLOWTYPE_TECHNICIAN_TO_SERVICEEXPERT_2.getCode(),
                            TypeDictionary.ORDERTYPE_SERVICEEXPERT_FEEDBACK.getCode(),
                            userT,synSfParam.getExpertsName());
                    if (conFlow < 1) {
                        throw new RuntimeException();
                    }

                } else {
                    // 未知Type
                    ParameterTool.writeResponse(response, 1, "未知操作类型：" + type);
                    return;
                }
                // 主动升级提交同步到SF
                escalationToSF(JSONObject.parseObject(JSON.toJSONString(synSfParam)));
                //新消息推送
                notifyConfigService.xinDoNotify("EscalationServiceImpl","submitEscalation",request.getEscalationOrderId());
            } finally {
                redisClientUtils.delkey("escalationOrder-" + (null == request.getWorkOrderId() ? request.getEscalationOrderId() : request.getEscalationOrderId()));
            }
        } else {
            //缺少必要参数
            ParameterTool.writeResponse(response, SMSEnum.type17.getIndex(), SMSEnum.type17.getName());
            return;
        }
        Long aLong = EscalationThreadLocal.get();
        EscalationOrderT escalationOrderT = escalationOrderTDao.selectByPrimaryKey(aLong);
        Map<String, Object> data = new HashMap<>();
        data.put("escalationOrderNo", escalationOrderT.getOrderNo());
        data.put("createTime", escalationOrderT.getCreateTime());
        data.put("escalationOrderId", escalationOrderT.getId());
        ParameterTool.writeSuccessResponse(response, data);
    }


    private CRMServiceApiImpl cRMServiceApiImpl = new CRMServiceApiImpl();

    /**
     * @description: 主动升级信息同步SF
     * @author: shiliqiang
     * @company: CTY Technology Co.,Ltd
     * @since: ${DATE} ${TIME}
     * @version: V1.0
     */
    public void escalationToSF(JSONObject parameter) {
        log.info("主动升级同步SF的接口入参：" + parameter);

        // 添加加密请求头
        Map<String, Object> tokenAndHostMap = cRMServiceApiImpl.getCCICrmTokenAndHost();
        if (tokenAndHostMap == null) {
            log.info("token获取失败：" + tokenAndHostMap);
        }
        // 添加token请求头
        Map<String, Object> headerParameter = cRMServiceApiImpl.addCCIEncryptionHeader(tokenAndHostMap);
        // 调取请求
        String channelHost = MapUtils.getString(tokenAndHostMap, "hostUrl", "") + CRMServiceConst.SYNC_ESCALATION_TOCRM;
        log.info("主动升级同步SF调用接口：" + channelHost);
        net.sf.json.JSONObject responseDate = CRMHttpClientUtil.httpPOSTRequest(channelHost, headerParameter, parameter);

        log.info("主动升级同步SF返回内容：" + responseDate);
//        if (responeEntity.getData().containsKey("CRMOrderNo")){
//            responeEntity.getData().get("CRMOrderNo");
//        }
    }

    // 获取工单详情列表
    @Override
    public void getEscalationOrderList(PagedRequest pagedRequest, GetEscalationOrderListRequest request) {
        // 通过负责人表查询与当前用户关联的升级工单
        PageHelper.startPage(pagedRequest.getPage(), pagedRequest.getPageSize());
        List<EscalationOrderT> escalationOrderList = new ArrayList<>();
        String roleNo = request.getRoleNo();
        UserT userT = UserThreadLocal.get();
        request.setUserId(userT.getId());
        switch (roleNo) {
            case "R0033":
                //服务技师
                escalationOrderList = escalationOrderTDao.getTechnicianOrderList(request);
                break;
            case "R0074":
                //区域工程师
                escalationOrderList = escalationOrderTDao.getFieldEngineerOrderList(request);
                break;
            case "R0091":
                //服务专家: 0：可以看到所有的DBU主动升级列表；其他的为当前服务专家的列表 sprint27修改需求，web端可配置是否可看全部升级单 0是不能，1是能
                EscalationExpertVisibilityRangeT escalationExpertVisibilityRangeT = escalationOrderTDao.getIsShowAllOrder(userT.getPhone());
                if (Objects.nonNull(escalationExpertVisibilityRangeT)) {
                    if (escalationExpertVisibilityRangeT.getIsShowAllOrder() == 0) {//0是仅能查看自己的工单，1展示所有升级工单
                        escalationOrderList = escalationOrderTDao.getExpertOrderList(request);
                    } else {//在全部工单页面可查看全部工单，其他页面仍是自己的工单
                        if (request.getOrderStatus().equals("0")) {
                            escalationOrderList = escalationOrderTDao.getAllExpertOrderList(request);
                        } else {
                            escalationOrderList = escalationOrderTDao.getExpertOrderList(request);
                        }
                    }
                } else {//可见配置中不存在，走之前的逻辑
                    if (request.getOrderStatus().equals("0")) {
                        escalationOrderList = escalationOrderTDao.getAllExpertOrderList(request);
                    } else {
                        escalationOrderList = escalationOrderTDao.getExpertOrderList(request);
                    }
                }
//                if (request.getOrderStatus().equals("0")) {
//                    escalationOrderList = escalationOrderTDao.getAllExpertOrderList(request);
//                } else {
//                    escalationOrderList = escalationOrderTDao.getExpertOrderList(request);
//                }
                break;
            case "R0041":
            case "R0069":
                //站长和信息员
                escalationOrderList = escalationOrderTDao.getStationMasterOrderList(request);
                break;
            default:
                ParameterTool.writeResponse(RequestContextHolder.getResponse(), SMSEnum.type28.getIndex(), SMSEnum.type28.getName());
                return;
        }
        PageInfo<EscalationOrderT> info = new PageInfo<>(escalationOrderList);
        PagedResponse<GetEscalationOrderResponse> response = new PagedResponse<>();
        List<GetEscalationOrderResponse> orderListResp = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(info.getList())) {
            GetEscalationOrderResponse getEscalationOrderResponse = new GetEscalationOrderResponse();
            for (EscalationOrderT escalationOrderT : info.getList()) {
                getEscalationOrderResponse = BeanUtils.convert(escalationOrderT, GetEscalationOrderResponse.class);
                List<EscalationReasonsResp> escalationReasonsRespList = getEscalationReasonListByOrderId(getEscalationOrderResponse.getId(), 2);
                getEscalationOrderResponse.setEscalationReasons(escalationReasonsRespList);
                List<EscalationSolutionResp> escalationSolutionRespList = getEscalationSolutionListByOrderId(getEscalationOrderResponse.getId(), 2);
                getEscalationOrderResponse.setEscalationSolutions(escalationSolutionRespList);
                orderListResp.add(getEscalationOrderResponse);
                getEscalationOrderResponse = null;
            }
        }
        response.setTotal(info.getTotal());
        response.setList(orderListResp);
        // 将获取列表给前端
        ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse(), response);
    }

    @Override
    public GetEscalationOrderDetailResponse getEscalationOrderDetail(Long orderId, String roleNo) {

        // 接收实体
        GetEscalationOrderDetailResponse detailResponse = new GetEscalationOrderDetailResponse();
        // 判断当前id是否有修改权限
        UserT userT = UserThreadLocal.get();
        if (roleNo.equals("R0091")) {
            List<EscalationReasonT> reasonList = escalationOrderTDao.getModifyAuth(orderId, userT.getId());
            if (reasonList.size() > 0) {
                detailResponse.setModifyAuth(0);
            } else {
                detailResponse.setModifyAuth(-1);
            }
        }
        GetEscalationOrderResponse orderResponse;
        List<GetEscalationFlowResponse> flowResponse = new ArrayList<>();
        EscalationOrderT escalationOrderT = escalationOrderTDao.selectByPrimaryKey(orderId);
        orderResponse = BeanUtils.convert(escalationOrderT, GetEscalationOrderResponse.class);
        List<GetWorkOrderListResponse> workOrderInfo = workOrderTDao.getWorkOrderListForEscalationById(escalationOrderT.getWorkOrderId());
        if (CollectionUtils.isNotEmpty(workOrderInfo)) {
            orderResponse.setESN(workOrderInfo.get(0).getESN());
            orderResponse.setWorkOrderNo(workOrderInfo.get(0).getOrderNo());
            orderResponse.setCustomerComplaint(workOrderInfo.get(0).getCustomerComplaint());
            orderResponse.setSMN(workOrderInfo.get(0).getSMN());
            String oemName = StringUtils.isNotEmpty(workOrderInfo.get(0).getOemName()) ? workOrderInfo.get(0).getOemName() : "";
            orderResponse.setOemName(oemName);
        }
        //添加时间差 和是否催单/是否当前专家待反馈
        String currentTime = LocalTimeUtil.getRealCurrentTime();
        TimeDiffAndType timeDiffAndType = escalationOrderTDao.selectTimeDiffAndType(orderId, currentTime);
        if (null != timeDiffAndType) {
            orderResponse.setTimeDiff(timeDiffAndType.getTimeDiff());
            orderResponse.setEscalationType(timeDiffAndType.getEscalationType());
            if ("3".equals(timeDiffAndType.getOrderStatus())) {
                if (StringUtils.isNotEmpty(timeDiffAndType.getPrincipalId())) {
                    if (userT.getId() == Long.valueOf(timeDiffAndType.getPrincipalId())) {
                        orderResponse.setIsPeople("1");
                    } else {
                        orderResponse.setIsPeople("0");
                    }
                } else {
                    orderResponse.setIsPeople("0");
                }
            } else {
                orderResponse.setIsPeople("0");
            }


        }
        // 1 获取升级原因列表
        List<EscalationReasonsResp> escalationReasonsRespList = getEscalationReasonListByOrderId(orderResponse.getId(), 1);
        // 目前两套原因相同，因此展示一条，若后期两套原因各不相同，即可将下面的for循环删掉
        if(CollectionUtils.isNotEmpty(escalationReasonsRespList)){
            for (int i = 0; i < escalationReasonsRespList.size(); i++) {
                EscalationReasonsResp escalationReasonsResp = escalationReasonsRespList.get(i);
                if (escalationReasonsResp.getEscalationType().equals("5")) {
                    escalationReasonsRespList.remove(i);
                } else {
                    List<EscalationReasonSupplementT> supplementTList = reasonSupplementTMapper.selectByReasonId(escalationReasonsResp.getId());
                    if (CollectionUtils.isNotEmpty(supplementTList)) {
                        List<EscalationReasonsResp.SupplementInfo> supplementInfoList = new ArrayList<>();
                        for (EscalationReasonSupplementT info : supplementTList) {
                            EscalationReasonsResp.SupplementInfo supplementInfo = new EscalationReasonsResp.SupplementInfo();
                            supplementInfo.setSupplementOrderNo(info.getOrderNo());
                            supplementInfo.setSupplementPartNo(info.getPartNo());
                            supplementInfo.setSupplementPartName(info.getPartName());
                            supplementInfo.setSupplementCount(info.getCount());
                            supplementInfoList.add(supplementInfo);
                            supplementInfo = null;
                        }
                        escalationReasonsResp.setSupplementInfo(supplementInfoList);
                    }
                }
            }
            orderResponse.setEscalationReasons(escalationReasonsRespList);
        }

        // 2 获取解决方案列表
        List<EscalationSolutionResp> escalationSolutionRespList = getEscalationSolutionListByOrderId(orderResponse.getId(), 1);
        orderResponse.setEscalationSolutions(escalationSolutionRespList);

        detailResponse.setOrderResponse(orderResponse);
        //获取时间轴
        List<EscalationFlowT> escalationFlowTList = escalationFlowTDao.getEscalationOrderTimeFlow(orderId);
        if (CollectionUtils.isNotEmpty(escalationFlowTList)) {
            GetEscalationFlowResponse convert;
            String typeStr1 = "1,2,3,4";    //发起主动升级
            String typeStr2 = "7,8";    //填写解决方案
            String typeStr3 = "1,4,5,6,9";
            String typeStr4 = "2,3,7";
            String typeStr5 = "8";
            for (EscalationFlowT escalationFlowT : escalationFlowTList) {
                convert = BeanUtils.convert(escalationFlowT, GetEscalationFlowResponse.class);
                UserT aceUser = loginDao.getUserByid(String.valueOf(escalationFlowT.getUserId()));
                if (aceUser != null) {
                    convert.setPhone(aceUser.getPhone());
                    convert.setContact(aceUser.getContact());
                }
                if (convert.getType() == 1) {
                    UserT fieldEngineer = workOrderTDao.getFieldEngineerByWorkOrderId(escalationOrderT.getWorkOrderId());
                    convert.setSecContact(fieldEngineer.getContact());
                    convert.setSecPhone(fieldEngineer.getPhone());
                }
                if (typeStr1.contains(String.valueOf(convert.getType()))) {
                    List<EscalationReasonT> escalationReasonTList = escalationReasonTDao.getEscalationReasonByOrderId(orderId, convert.getType());
                    EscalationReasonT escalationReasonT = escalationReasonTList.get(0);
                    convert.setReasonKey(escalationReasonT.getReasonKey());
                    convert.setReasonValue(escalationReasonT.getReasonValue());
                    convert.setSupplementReason(escalationReasonT.getSupplementReason());
                } else if (typeStr2.contains(String.valueOf(convert.getType()))) {
                    List<EscalationSolutionT> escalationSolutionTList = escalationSolutionTDao.getEscalationSolutionListByOrderId(orderId);
                    if (7 == convert.getType()) {
                        assert escalationSolutionRespList != null;
                        EscalationSolutionT escalationSolutionT = escalationSolutionTList.get(escalationSolutionRespList.size() - 1);
                        convert.setSolution(escalationSolutionT.getSolution());
                        convert.setAttachmentList(escalationSolutionT.getAttachmentList());
                    } else if (8 == convert.getType()) {
                        EscalationSolutionT escalationSolutionT = escalationSolutionTList.get(0);
                        convert.setSolution(escalationSolutionT.getSolution());
                        convert.setAttachmentList(escalationSolutionT.getAttachmentList());
                    }
                }
                //添加角色名称
                if (typeStr3.contains(String.valueOf(convert.getType()))) {
                    convert.setRoleName("服务技师");
                } else if (typeStr4.contains(String.valueOf(convert.getType()))) {
                    convert.setRoleName("区域工程师");
                } else if (typeStr5.contains(String.valueOf(convert.getType()))) {
                    convert.setRoleName("服务专家");
                }
                flowResponse.add(convert);
                convert = null;
            }
        }
        detailResponse.setFlowResponse(flowResponse);
        return detailResponse;
    }

    // 获取可升级服务工单
    @Override
    public void getWorkOrderListForEscalation(PagedRequest pagedRequest, String keyword, String roleNo) {
        UserT userT = UserThreadLocal.get();
        PageHelper.startPage(pagedRequest.getPage(), pagedRequest.getPageSize());
        List<GetWorkOrderListResponse> orderList = new ArrayList<>();
        if (roleNo.equals("R0033")) {
            GetWorkOrderListRequest getWorkOrderListRequest = new GetWorkOrderListRequest();
            getWorkOrderListRequest.setUserId(userT.getId());
            getWorkOrderListRequest.setKeyword(keyword);
            orderList = workOrderTDao.getTechnicianWorkOrderListForEscalation(getWorkOrderListRequest);
        } else if (roleNo.equals("R0074")) {
            GetWorkOrderListRequest getWorkOrderListRequest = new GetWorkOrderListRequest();
            getWorkOrderListRequest.setUserId(userT.getId());
            getWorkOrderListRequest.setKeyword(keyword);
            orderList = workOrderTDao.getFieldEngineerWorkOrderListForEscalation(getWorkOrderListRequest);
        } else {
            // 未知roleNo
            ParameterTool.writeResponse(RequestContextHolder.getResponse(), 1, "未知操作类型：" + roleNo);
            return;
        }
        PageInfo<GetWorkOrderListResponse> info = new PageInfo<>(orderList);
        PagedResponse<GetWorkOrderListResponse> response = new PagedResponse<>();
        response.setTotal(info.getTotal());
        response.setList(info.getList());
        ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse(), response);
    }

    /**
     * type: 1 获取催单信息；2. 进行催单操作
     * 流程说明：1. 催单只进行两个，超过则无法再催单，首次催单和再次催单的提示语不同；2. 若时间超过1h，则直接跳转至“待服务专家审核”
     */
    @Transactional
    @Override
    public void remindFeedback(Long orderId, Integer type, String number) throws Exception {
        EscalationOrderT escalationOrderT = escalationOrderTDao.selectByPrimaryKey(orderId);
        EscalationPrincipalT escalationPrincipalT = escalationPrincipalTDao.selectByOrderId(escalationOrderT.getId());
        EscalationReasonT escalationReasonT = escalationReasonTDao.getEscalationReasonByOrderId(orderId, 1).get(0);
        if (null == escalationPrincipalT.getPrincipalId()) {
            ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -24);
            return;
        }
        EscalationRemindBean remindBeanResp = new EscalationRemindBean();   //返回数据类型
        //首先判断该工单状态是否变更了
        if (escalationOrderT.getStatus() != 1) {
            ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -23);
            return;
        }
        UserT userT = UserThreadLocal.get();
        // 1 获取催单信息; 2 催单操作
        if (type.equals(1)) {
            long subTime = Date_Util.getSubTime(escalationOrderT.getCreateTime(), LocalTimeUtil.getRealCurrentTime(), 2);
            // 1. 超过1h，则返回number=-1，代表已经超过1H
            if (subTime >= 60) {
                remindBeanResp.setNumber("-1");
                remindBeanResp.setOrderNo(escalationOrderT.getOrderNo());
                ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse(), remindBeanResp);
                return;
            }
            // 2. 若<1H，催单记录放置于Redis中，一次/二次提醒语句；实体类中添加次数，用于后期催单次数增加的拓展
            String conNum = redisClientUtils.hget(RedisKeys.getRemindStatusForEscalation(), escalationOrderT.getOrderNo());
            if (null == conNum) {
                //若为空，则为首次提醒
                redisClientUtils.hset(RedisKeys.getRemindStatusForEscalation(), escalationOrderT.getOrderNo(), "0");
                remindBeanResp.setNumber("0");
                remindBeanResp.setOrderNo(escalationOrderT.getOrderNo());
            } else if (Integer.valueOf(conNum) >= 2) {
                // 第三次催单，不修改redis数据
                UserT orderPrincipal = loginDao.getUserByid(String.valueOf(escalationPrincipalT.getPrincipalId()));
                remindBeanResp.setNumber(conNum);
                remindBeanResp.setContact(orderPrincipal.getContact());
                remindBeanResp.setUserPhone(orderPrincipal.getPhone());
            } else {
                // 第二次提醒: 返回数据
                remindBeanResp.setNumber(conNum);
                remindBeanResp.setOrderNo(escalationOrderT.getOrderNo());
            }
            //主动升级同步给SF对象
            SynSfParam synSfParam = new SynSfParam();
            //查询工单
            Map<String, Object> orderInfoMap = workOrderTDao.getOrderById(escalationOrderT.getWorkOrderId());
            synSfParam.setWorkOrderNo(orderInfoMap.get("OrderNo") + "");
            synSfParam.setUpgradeDescription(orderInfoMap.get("CustomerComplaint") + "");
            synSfParam.setUpgradeAppNo(escalationOrderT.getOrderNo());
            //同步给SF表单类型
            synSfParam.setUpgradeFormType(FormType.URGING_TREATMENT.getMessage());
            //同步给SF表单提交人角色
            synSfParam.setUpgradeSubmitUser(RoleType.SERVICE_TECHNICIAN.getMessage());
            synSfParam.setUpgradeSubmitUserName(userT.getContact());
            synSfParam.setUpgradeSubmitUserPhone(userT.getPhone());
            synSfParam.setUpgradeFormStatus(FormStatusType.PROCESSING.getMessage());
            synSfParam.setUpgradeSubmitDateTime(LocalTimeUtil.getRealCurrentTime());
            synSfParam.setUpgradeStage(RoleType.REGIONAL_ENGINEER.getMessage());
            // 催单流程同步到SF
            escalationToSF(JSONObject.parseObject(JSON.toJSONString(synSfParam)));

            ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse(), remindBeanResp);
            return;
        }
        // 进行催单操作
        if (type.equals(2)) {
            // 超过1h，则更新状态至"待服务专家审核"
            if ("-1".equals(number)) {
                //判断是否有对应的服务专家
                int con = isPrincipalExisted("5", String.valueOf(escalationReasonT.getReasonKey()), loginDao.getUserByid(String.valueOf(escalationPrincipalT.getPrincipalId())), null);
                if (con == -2) {
                    ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -27);
                    return;
                }
                // 更新order表单信息
                escalationOrderT.setStatus(3);
                escalationOrderT.setUpdator(UserThreadLocal.get().getId());
                escalationOrderT.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
                int conOrder = escalationOrderTDao.updateByPrimaryKeySelective(escalationOrderT);
                if (conOrder < 1) {
                    throw new RuntimeException();
                }
                // 新增orderReason表单
                EscalationReasonT lastReasonByOrderId = escalationReasonTDao.getLastReasonByOrderId(orderId);
                SubmitReasonRequest submitReasonRequest = new SubmitReasonRequest();
                submitReasonRequest.setType(String.valueOf(TypeDictionary.ESCALATIONTYPE_TECHNICIAN_TO_SERVICEEXPERT_REMIND.getCode()));
                submitReasonRequest.setEscalationOrderId(orderId);
                submitReasonRequest.setReasonKey(String.valueOf(lastReasonByOrderId.getReasonKey()));
                submitReasonRequest.setReasonValue(lastReasonByOrderId.getReasonValue());
                submitReasonRequest.setSupplementReason(lastReasonByOrderId.getSupplementReason());
                insertEscalationReasonT(submitReasonRequest, userT, new SynSfParam());
                // 新增：流水，更新成功，则添加流水
                int conFlow = insertEscalationFlowT(orderId,
                        TypeDictionary.FLOWTYPE_TECHNICIAN_TO_SERVICEEXPERT_REMIND.getCode(),
                        TypeDictionary.ORDERTYPE_SERVICEEXPERT_FEEDBACK.getCode(),
                        userT,null);
                if (conFlow < 1) {
                    throw new RuntimeException();
                }
                EscalationThreadLocal.set(escalationOrderT.getId());
                ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse(), "已升级至待服务专家反馈");
                return;
            }
            String conStr = "0,1,2";    //0 首次催单；1 二次催单； 2 三次催单的时候
            if (null == number || !conStr.contains(number)) {
                ParameterTool.writeResponse(RequestContextHolder.getResponse(), SMSEnum.type18.getIndex(), SMSEnum.type18.getName());
                return;
            }
            String conNum = redisClientUtils.hget(RedisKeys.getRemindStatusForEscalation(), escalationOrderT.getOrderNo());
            if (null != conNum) {
                int conNumInt = Integer.parseInt(conNum);
                if (conNumInt < 2) {
                    // 流水
/*                    int conFlow = insertEscalationFlowT(orderId,
                            String.valueOf(TypeDictionary.ESCALATIONTYPE_FLOWTYPE_REMIND_LESSTHANONEHOUR.getCode()),
                            TypeDictionary.ORDERTYPE_FIELDENGINEER_FEEDBACK.getCode(),
                            userT);
                    if (conFlow < 1) {
                        throw new RuntimeException();
                    }*/
                    redisClientUtils.hset(RedisKeys.getRemindStatusForEscalation(), escalationOrderT.getOrderNo(), String.valueOf(++conNumInt));
                    EscalationThreadLocal.set(escalationOrderT.getId());
                    // 首次提醒和第一次提醒，都正常提醒
                    ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse());
                    return;
                }
            }
            //催单失败
            ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -22);
        }
    }

    // 提交解决方案
    @Transactional
    @Override
    public void submitEscalationSolution(SubmitSolutionRequest request) throws Exception {
        EscalationSolutionT escalationSolutionT = new EscalationSolutionT();
        String time = LocalTimeUtil.getRealCurrentTime();
        if (null == request.getOrderId() || null == request.getSolution() || null == request.getRoleId() || null == request.getRoleNo()) {
            //缺少必要参数
            ParameterTool.writeResponse(RequestContextHolder.getResponse(), SMSEnum.type17.getIndex(), SMSEnum.type17.getName());
            return;
        }
        UserT userT = UserThreadLocal.get();

        Long solutionId = null;

        //更改：升级工单
        EscalationOrderT escalationOrderT = escalationOrderTDao.selectByPrimaryKey(request.getOrderId());
        if (null == escalationOrderT) {
            ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -18);
            return;
        }
        if (escalationOrderT.getStatus() == 4 || escalationOrderT.getStatus() == 5) {
            ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -28);
            return;
        }
        Map<String, Object> orderInfoMap = workOrderTDao.getOrderById(escalationOrderT.getWorkOrderId());
        //主动升级同步给SF对象
        SynSfParam synSfParam = new SynSfParam();
        //主动升级同步给SF添加公共数据
        synSfParam.setWorkOrderNo(orderInfoMap.get("OrderNo") + "");
        synSfParam.setUpgradeDescription(orderInfoMap.get("CustomerComplaint") + "");
        synSfParam.setUpgradeAppNo(escalationOrderT.getOrderNo());
        synSfParam.setUpgradeSubmitUserName(userT.getContact());
        synSfParam.setUpgradeSubmitUserPhone(userT.getPhone());
        synSfParam.setUpgradeSubmitDateTime(time);
        synSfParam.setUpgradeFormStatus(FormStatusType.FEEDBACK.getMessage());
        synSfParam.setSolution(request.getSolution());
        synSfParam.setSolutionTime(time);
        synSfParam.setUpgradeStage(RoleType.SERVICE_TECHNICIAN.getMessage());
        if ("R0074".equals(request.getRoleNo())) {        // 区域工程师
            try {
                // 加锁处理，避免发生多次注册。
                if (!redisClientUtils.lock("escalationRemind-" + escalationOrderT.getId(), 60L)) {
                    ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -98);
                    return;
                }
                //同步给SF表单类型
                synSfParam.setUpgradeFormType(FormType.NORMAL_UPGRADE.getMessage());
                //synSfParam.setUpgradeStage(RoleType.REGIONAL_ENGINEER.getMessage());
                synSfParam.setUpgradeSubmitUser(RoleType.REGIONAL_ENGINEER.getMessage());

                escalationOrderT.setUpdator(userT.getId());
                escalationOrderT.setUpdateTime(time);
                escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_TECHNICIAN_CONFIRMING.getCode());
                int conOrder = escalationOrderTDao.updateByPrimaryKeySelective(escalationOrderT);
                if (conOrder < 1) {
                    throw new RuntimeException();
                }
                //新增：负责人表
                int conPrincipal = insertEscalationPrincipal("5", request.getOrderId(), null, userT);
                if (conPrincipal < 1) {
                    throw new RuntimeException();
                }
                //新增：流水
                int conFlow = insertEscalationFlowT(request.getOrderId(),
                        TypeDictionary.FLOWTYPE_FEEDBACK_FROM_FIELDENGINEER.getCode(),
                        TypeDictionary.ORDERTYPE_TECHNICIAN_CONFIRMING.getCode(),
                        userT,null);
                if (conFlow < 1) {
                    throw new RuntimeException();
                }

            } finally {
                redisClientUtils.delkey("escalationRemind-" + escalationOrderT.getId());
            }
        } else if ("R0091".equals(request.getRoleNo())) {            // 服务专家
            solutionId = request.getSolutionId();
            try {
                // 加锁处理，避免发生多次注册。
                if (!redisClientUtils.lock("escalationRemind-" + escalationOrderT.getId(), 60L)) {
                    ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -98);
                    return;
                }
                //同步给SF表单类型
                List<EscalationFlowT> flowTList = escalationFlowTDao.getEscalationOrderTimeFlow(escalationOrderT.getId());
                //是否为技师再升级
                boolean ifUpgrade = false;
                if(CollectionUtils.isNotEmpty(flowTList)){
                    for(EscalationFlowT flowT : flowTList){
                        if(TypeDictionary.FLOWTYPE_TECHNICIAN_TO_SERVICEEXPERT.getCode().equals(flowT.getType())
                                || TypeDictionary.FLOWTYPE_TECHNICIAN_TO_SERVICEEXPERT_2.getCode().equals(flowT.getType())){
                            ifUpgrade = true;
                        }
                    }
                }
                synSfParam.setUpgradeSubmitUser(RoleType.SERVICE_EXPERT.getMessage());
                if(ifUpgrade){
                    synSfParam.setUpgradeFormType(FormType.RE_UPGRADE.getMessage());
                } else{
                    synSfParam.setUpgradeFormType(FormType.NORMAL_UPGRADE.getMessage());
                }
                //synSfParam.setUpgradeStage(RoleType.SERVICE_EXPERT.getMessage());
                escalationOrderT.setUpdator(userT.getId());
                escalationOrderT.setUpdateTime(time);
                escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_TECHNICIAN_CONFIRMING_FROMSERVICEEXPERT.getCode());
                int conOrder = escalationOrderTDao.updateByPrimaryKeySelective(escalationOrderT);
                if (conOrder < 1) {
                    throw new RuntimeException();
                }
                //新增：负责人表
                int conPrincipal = insertEscalationPrincipal("6", request.getOrderId(), null, userT);
                if (conPrincipal < 1) {
                    throw new RuntimeException();
                }

                //新增：流水
                int conFlow = insertEscalationFlowT(request.getOrderId(),
                        TypeDictionary.FLOWTYPE_FEEDBACK_FROM_SERVICEEXPERT.getCode(),
                        TypeDictionary.ORDERTYPE_TECHNICIAN_CONFIRMING_FROMSERVICEEXPERT.getCode(),
                        userT,null);
                if (conFlow < 1) {
                    throw new RuntimeException();
                }
            } finally {
                redisClientUtils.delkey("escalationRemind-" + escalationOrderT.getId());
            }
        }
        int conSolution = 0;
        if (solutionId != null) {
            EscalationSolutionT solution = escalationSolutionTDao.selectByPrimaryKey(solutionId);
            solution.setSolution(request.getSolution());
            solution.setProviderId(userT.getId());
            solution.setAttachmentList(request.getAttachmentList());
            solution.setFlag(0);
            solution.setUpdator(userT.getId());
            solution.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
            conSolution = escalationSolutionTDao.updateByPrimaryKeySelective(solution);
        } else {
            //新增：解决方案表
            escalationSolutionT.setOrderId(request.getOrderId());
            List<EscalationReasonT> escalationReasonByOrderId = escalationReasonTDao.getEscalationReasonByOrderId(request.getOrderId(), null);
            escalationSolutionT.setOrderReasonId(escalationReasonByOrderId.get(0).getId());
            escalationSolutionT.setProviderId(userT.getId());
            escalationSolutionT.setSolution(request.getSolution());
            escalationSolutionT.setAttachmentList(request.getAttachmentList());
            escalationSolutionT.setFlag(0);
            escalationSolutionT.setCreator(userT.getId());
            escalationSolutionT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
            conSolution = escalationSolutionTDao.insertSelective(escalationSolutionT);
        }
        if (conSolution < 1) {
            throw new RuntimeException();
        }
        UserT user = userTDao.selectById(escalationOrderT.getCreator());
        if(null != user){
            synSfParam.setUpgradeStageName(user.getContact());
        }
        // 把专家或工程师的解决方案同步到SF
        escalationToSF(JSONObject.parseObject(JSON.toJSONString(synSfParam)));

        EscalationThreadLocal.set(request.getOrderId());
        ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse());
    }

    // 技师确认解决方案接口
    @Transactional
    @Override
    public void confirmEscalationSolution(String roleNo, Long orderId) throws Exception {
        if (!"R0033".equals(roleNo)) {
            //非技师不可进行该操作
            ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -22);
            return;
        }
        UserT userT = UserThreadLocal.get();
        EscalationOrderT escalationOrderT = escalationOrderTDao.selectByPrimaryKey(orderId);

        //修改：升级工单
        if (null == escalationOrderT) {
            ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -18);
            return;
        }
        if (escalationOrderT.getStatus() == 4 || escalationOrderT.getStatus() == 5) {
            ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -28);
            return;
        }
        if (2 != escalationOrderT.getStatus() && 6 != escalationOrderT.getStatus()) {
            ParameterTool.writeErrorResponse(RequestContextHolder.getResponse(), -22);
            return;
        }
        //新增：流水
        int conFlow;
        if (2 == escalationOrderT.getStatus()) {
            conFlow = insertEscalationFlowT(orderId, TypeDictionary.FLOWTYPE_CONFIRM_FOR_FIELDENGINEER.getCode(), TypeDictionary.ORDERTYPE_FINISHED.getCode(), userT,null);
        } else {
            conFlow = insertEscalationFlowT(orderId, TypeDictionary.FLOWTYPE_CONFIRM_FOR_SERVICEEXPERT.getCode(), TypeDictionary.ORDERTYPE_FINISHED.getCode(), userT,null);
        }
        if (conFlow < 1) {
            throw new RuntimeException();
        }
        String time = LocalTimeUtil.getRealCurrentTime();
        escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_FINISHED.getCode());
        escalationOrderT.setUpdator(userT.getId());
        escalationOrderT.setUpdateTime(time);
        //主动升级同步给SF对象
        SynSfParam synSfParam = new SynSfParam();
        Map<String, Object> orderInfoMap = workOrderTDao.getOrderById(escalationOrderT.getWorkOrderId());
        synSfParam.setWorkOrderNo(orderInfoMap.get("OrderNo") + "");
        synSfParam.setUpgradeAppNo(escalationOrderT.getOrderNo());
        //synSfParam.setUpgradeStage(RoleType.SERVICE_TECHNICIAN.getMessage());
        synSfParam.setUpgradeSubmitUser(RoleType.SERVICE_TECHNICIAN.getMessage());
        synSfParam.setUpgradeFormStatus(FormStatusType.COMPLETED.getMessage());
        synSfParam.setUpgradeSubmitUserName(userT.getContact());
        synSfParam.setUpgradeSubmitUserPhone(userT.getPhone());
        synSfParam.setUpgradeSubmitDateTime(time);
        synSfParam.setUpgradeEndDateTime(time);
        //区域工程师姓名
        UserT engineerUserT = workOrderTDao.getFieldEngineerByWorkOrderId(escalationOrderT.getWorkOrderId());
        if(null != engineerUserT){
            synSfParam.setUpgradeStageName(engineerUserT.getContact());
        }
        //同步给SF表单类型

        List<EscalationFlowT> flowTList = escalationFlowTDao.getEscalationOrderTimeFlow(escalationOrderT.getId());
        //是否为技师再升级
        boolean ifUpgrade = false;
        if(CollectionUtils.isNotEmpty(flowTList)){
            for(EscalationFlowT flowT : flowTList){
                if(TypeDictionary.FLOWTYPE_TECHNICIAN_TO_SERVICEEXPERT.getCode().equals(flowT.getType())
                        || TypeDictionary.FLOWTYPE_TECHNICIAN_TO_SERVICEEXPERT_2.getCode().equals(flowT.getType())){
                    ifUpgrade = true;
                }
            }
        }
        if(ifUpgrade){
            synSfParam.setUpgradeFormType(FormType.RE_UPGRADE.getMessage());
        } else{
            synSfParam.setUpgradeFormType(FormType.NORMAL_UPGRADE.getMessage());
        }
//        List<UserT> engineersList = escalationNotifyService.getEngineers(escalationOrderT.getId());
//        if (engineersList != null && engineersList.size() > 0) {
//            // 在升级时单子直接到专家
//            synSfParam.setEngineerName(engineersList.get(0).getContact());
//            synSfParam.setEngineerPhone(engineersList.get(0).getPhone());
//        }
//        List<UserT> expertList = escalationNotifyService.getReasonTypeExpert(escalationOrderT.getId());
//        if (expertList != null && expertList.size() > 0) {
//            synSfParam.setServiceExpertName(expertList.get(0).getContact());
//            synSfParam.setServiceExpertPhone(expertList.get(0).getPhone());
//        }
        // 查询解决方案，取出最新的一条
        EscalationSolutionT escalationSolutionT = escalationSolutionTDao.getLastEscalationSolutionByOrderId(orderId);
        if (escalationSolutionT != null) {
            synSfParam.setSolution(escalationSolutionT.getSolution());
            if (StringUtils.isEmpty(escalationSolutionT.getUpdateTime())) {
                synSfParam.setSolutionTime(escalationSolutionT.getCreateTime());
            } else {
                synSfParam.setSolutionTime(escalationSolutionT.getUpdateTime());
            }
        }
        int conOrder = escalationOrderTDao.updateByPrimaryKeySelective(escalationOrderT);
        if (conOrder < 1) {
            throw new RuntimeException();
        }

        //新增：负责人表
        int conPrincipal = insertEscalationPrincipal("7", orderId, null, userT);
        if (conPrincipal < 1) {
            throw new RuntimeException();
        }
        //技师确认解决方案同步到SF
        escalationToSF(JSONObject.parseObject(JSON.toJSONString(synSfParam)));
        EscalationThreadLocal.set(escalationOrderT.getId());
        ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse());
    }

    /**
     * @param workOrderId
     * @param type        1: 服务工单异常关闭;2: 服务工单已取消;3: 服务工单已完成
     */
    @Override
    public void disableEscalationByWorkOrderId(Long workOrderId, Integer type) {
        try {
            log.info("[disableEscalationByWorkOrderId接口调用]：workOrderId：" + workOrderId + ";type" + type);
            String typeStr = "1,2,3";
            if (!typeStr.contains(String.valueOf(type))) {
                //参数不正确
                log.error(SMSEnum.type18.getName() + "(type): " + type);
                return;
            }
            UserT userT = UserThreadLocal.get();
            if (null == userT) {
                //crm操作的工单没有用户信息，为防止主动升级报错，这里给操作人一个默认的用户
                userT = loginDao.getUserMsgByUserName("CRM_ADMIN");
                UserThreadLocal.set(userT);
            }
            String time = LocalTimeUtil.getRealCurrentTime();
            EscalationOrderT escalationOrderT = escalationOrderTDao.selectByWorkOrderId(workOrderId);
            //主动升级同步给SF对象
            SynSfParam synSfParam = new SynSfParam();
            log.info("[disableEscalationByWorkOrderId接口调用]：escalationOrderT详情：" + JsonUtils.toJsonString(escalationOrderT));
            if (null != escalationOrderT && escalationOrderT.getStatus() != 4 && escalationOrderT.getStatus() != 5) {
                escalationOrderT.setUpdator(userT.getId());
                escalationOrderT.setUpdateTime(time);
                // 新增流水
                List<EscalationSolutionT> escalationSolutionList = escalationSolutionTDao.getEscalationSolutionListByOrderId(escalationOrderT.getId());
                if (type.equals(1)) {
                    // 服务工单维修完成时调用
                    // 服务工单状态变更为维修完成时，如果服务工单存在“主动升级工单”，且工单状态为“升级未反馈”，则工单状态变为升级结束, 服务工单状态变成为维修完成时，如果服务工单存在“主动升级工单”，且工单状态为“服务技师未确认方案是否有效”，则工单状态变为升级完成
                    // 经与白冰涛沟通：只要工单无反馈方案，都为升级结束，只要有反馈方案，都为升级完成，王伟提供话术
                    if (CollectionUtils.isNotEmpty(escalationSolutionList)) {
                        escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_FINISHED.getCode());
                        synSfParam.setUpgradeFormStatus(FormStatusType.COMPLETED.getMessage());
                        insertEscalationFlowT(escalationOrderT.getId(), TypeDictionary.FLOWTYPE_WORKORDER_SHUTDOWN_2.getCode(), TypeDictionary.ORDERTYPE_FINISHED.getCode(), userT,null);
                    } else {
                        escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_SHUTDOWN.getCode());
                        synSfParam.setUpgradeFormStatus(FormStatusType.ORDERFINISH.getMessage());
                        insertEscalationFlowT(escalationOrderT.getId(), TypeDictionary.FLOWTYPE_WORKORDER_SHUTDOWN_1.getCode(), TypeDictionary.ORDERTYPE_SHUTDOWN.getCode(), userT,null);
                    }
                } else if (type.equals(2)) {
                    escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_SHUTDOWN.getCode());
                    synSfParam.setUpgradeFormStatus(FormStatusType.ORDERFINISH.getMessage());
                    insertEscalationFlowT(escalationOrderT.getId(), TypeDictionary.FLOWTYPE_WORKORDER_CANCEL.getCode(), TypeDictionary.ORDERTYPE_SHUTDOWN.getCode(), userT,null);
                } else if (type.equals(3)) {
                    if (CollectionUtils.isNotEmpty(escalationSolutionList)) {
                        escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_FINISHED.getCode());
                        synSfParam.setUpgradeFormStatus(FormStatusType.COMPLETED.getMessage());
                        insertEscalationFlowT(escalationOrderT.getId(), TypeDictionary.FLOWTYPE_WORKORDER_FINISHED_2.getCode(), TypeDictionary.ORDERTYPE_FINISHED.getCode(), userT,null);
                    } else {
                        escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_SHUTDOWN.getCode());
                        synSfParam.setUpgradeFormStatus(FormStatusType.ORDERFINISH.getMessage());
                        insertEscalationFlowT(escalationOrderT.getId(), TypeDictionary.FLOWTYPE_WORKORDER_FINISHED_1.getCode(), TypeDictionary.ORDERTYPE_SHUTDOWN.getCode(), userT,null);
                    }
                }
                escalationOrderTDao.updateByPrimaryKeySelective(escalationOrderT);

                Map<String, Object> orderInfoMap = workOrderTDao.getOrderById(workOrderId);
                synSfParam.setWorkOrderNo(orderInfoMap.get("OrderNo") + "");
                synSfParam.setUpgradeAppNo(escalationOrderT.getOrderNo());
                //synSfParam.setUpgradeStage(RoleType.SERVICE_TECHNICIAN.getMessage());
                synSfParam.setUpgradeSubmitUser(RoleType.SERVICE_TECHNICIAN.getMessage());
                synSfParam.setUpgradeSubmitUserName(userT.getContact());
                synSfParam.setUpgradeSubmitUserPhone(userT.getPhone());
                synSfParam.setUpgradeSubmitDateTime(time);
                synSfParam.setUpgradeEndDateTime(time);
                //同步给SF表单类型

                List<EscalationFlowT> flowTList = escalationFlowTDao.getEscalationOrderTimeFlow(escalationOrderT.getId());
                //是否为技师再升级
                boolean ifUpgrade = false;
                if(CollectionUtils.isNotEmpty(flowTList)){
                    for(EscalationFlowT flowT : flowTList){
                        if(TypeDictionary.FLOWTYPE_TECHNICIAN_TO_SERVICEEXPERT.getCode().equals(flowT.getType())
                                || TypeDictionary.FLOWTYPE_TECHNICIAN_TO_SERVICEEXPERT_2.getCode().equals(flowT.getType())){
                            ifUpgrade = true;
                        }
                    }
                }
                if(ifUpgrade){
                    synSfParam.setUpgradeFormType(FormType.RE_UPGRADE.getMessage());
                } else{
                    synSfParam.setUpgradeFormType(FormType.NORMAL_UPGRADE.getMessage());
                }

                // 查询解决方案，取出最新的一条
                EscalationSolutionT escalationSolutionT = escalationSolutionTDao.getLastEscalationSolutionByOrderId(escalationOrderT.getId());
                if (escalationSolutionT != null) {
                    synSfParam.setSolution(escalationSolutionT.getSolution());
                    if (StringUtils.isEmpty(escalationSolutionT.getUpdateTime())) {
                        synSfParam.setSolutionTime(escalationSolutionT.getCreateTime());
                    } else {
                        synSfParam.setSolutionTime(escalationSolutionT.getUpdateTime());
                    }
                }
                //技师确认解决方案同步到SF
                escalationToSF(JSONObject.parseObject(JSON.toJSONString(synSfParam)));
                EscalationThreadLocal.set(escalationOrderT.getId());
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    private List<EscalationSolutionResp> getEscalationSolutionListByOrderId(Long orderId, Integer type) {
        List<EscalationSolutionResp> listResp = new ArrayList<>();
        List<EscalationSolutionT> escalationSolutionRespList = new ArrayList<>();
        if (type.equals(1)) {
            escalationSolutionRespList = escalationSolutionTDao.getEscalationSolutionListByOrderId(orderId);
        } else if (type.equals(2)) {
            escalationSolutionRespList = escalationSolutionTDao.getEscalationSolutionByOrderId(orderId);
        }
        if (CollectionUtils.isNotEmpty(escalationSolutionRespList)) {
            EscalationSolutionResp convert;
            for (EscalationSolutionT escalationSolutionT : escalationSolutionRespList) {
                convert = BeanUtils.convert(escalationSolutionT, EscalationSolutionResp.class);
                Integer escalationType = escalationReasonTDao.selectByPrimaryKey(convert.getOrderReasonId()).getEscalationType();
                if (1 == escalationType) {
                    convert.setType(7);
                } else if (2 == escalationType || 3 == escalationType || 4 == escalationType || 5 == escalationType || 6 == escalationType) {
                    convert.setType(8);
                }
                listResp.add(convert);
                convert = null;
            }
            return listResp;
        }
        return null;
    }

    private List<EscalationReasonsResp> getEscalationReasonListByOrderId(Long orderId, Integer con) {
        List<EscalationReasonsResp> listResp = new ArrayList<>();
        List<EscalationReasonT> escalationReasonsRespList = new ArrayList<>();
        if (con.equals(1)) {
            escalationReasonsRespList = escalationReasonTDao.getEscalationReasonListByOrderId(orderId);
        } else if (con.equals(2)) {
            escalationReasonsRespList = escalationReasonTDao.getEscalationReasonByOrderId(orderId, null);
        }
        if (CollectionUtils.isNotEmpty(escalationReasonsRespList)) {
            EscalationReasonsResp convert;
            for (EscalationReasonT escalationReasonT : escalationReasonsRespList) {
                convert = BeanUtils.convert(escalationReasonT, EscalationReasonsResp.class);
                listResp.add(convert);
                convert = null;
            }
            return listResp;
        }
        return null;
    }

    //新增：负责人表：1，技师创建（该人为服务工单的区域工程师）;2.区域工程师升级（为本人）;3.区域工程师创建（为本人）；4 技师再升级（一样为本人）;5 区域工程师反馈；6 服务专家反馈;7 技师确认;8 待技师确认-技师拒绝专家反馈内容，继续升级
    public int insertEscalationPrincipal(String type, Long escalationOrderId, Long workOrderId, UserT userT) {
        EscalationPrincipalT escalationPrincipalT = new EscalationPrincipalT();

        escalationPrincipalT.setOrderId(escalationOrderId);
        String typeStr1 = "2,3,4,8";  //待专家反馈
        String typeStr2 = "7";    //工单完成
        String typeStr3 = "5";   //区域工程师反馈，待技师确认
        String typeStr4 = "6";   //服务专家反馈，待技师确认
        if ("1".equals(type)) {
            escalationPrincipalT.setOrderStatus(TypeDictionary.ORDERTYPE_FIELDENGINEER_FEEDBACK.getCode());
            UserT userT1 = workOrderTDao.getFieldEngineerByWorkOrderId(workOrderId);
            escalationPrincipalT.setPrincipalId(userT1.getId());
        } else if (typeStr1.contains(type)) {
            escalationPrincipalT.setOrderStatus(TypeDictionary.ORDERTYPE_SERVICEEXPERT_FEEDBACK.getCode());
            escalationPrincipalT.setPrincipalId(userT.getId());
        } else if (typeStr2.contains(type)) {
            escalationPrincipalT.setOrderStatus(TypeDictionary.ORDERTYPE_FINISHED.getCode());
            escalationPrincipalT.setPrincipalId(userT.getId());
        } else if (typeStr3.contains(type)) {
            escalationPrincipalT.setOrderStatus(TypeDictionary.ORDERTYPE_TECHNICIAN_CONFIRMING.getCode());
            escalationPrincipalT.setPrincipalId(userT.getId());
        } else if (typeStr4.contains(type)) {
            escalationPrincipalT.setOrderStatus(TypeDictionary.ORDERTYPE_TECHNICIAN_CONFIRMING_FROMSERVICEEXPERT.getCode());
            escalationPrincipalT.setPrincipalId(userT.getId());
        }
        escalationPrincipalT.setFlag(0);
        escalationPrincipalT.setCreator(userT.getId());
        escalationPrincipalT.setCreateTime(LocalTimeUtil.getRealCurrentTime());

        return escalationPrincipalTDao.insertSelective(escalationPrincipalT);
    }

    // true:可继续执行；false：不能继续执行
    private boolean getValidationByOrderId(SubmitReasonRequest request) {
        //Type  1：技师创建工单；2：工程师升级工单；3：区域工程师创建工单；4：技师再升级；6：技师继续升级至服务专家
        String type = request.getType();
        EscalationOrderT escalationOrderT;
        if (null == request.getWorkOrderId()) {
            escalationOrderT = escalationOrderTDao.selectByPrimaryKey(request.getEscalationOrderId());
        } else {
            escalationOrderT = escalationOrderTDao.selectByWorkOrderId(request.getWorkOrderId());
        }

        if ("1,3".contains(type) && null == escalationOrderT) {  //当前无次工单，则可新建
            return true;
        } else if ("2".equals(type) && null != escalationOrderT) {   // 区域工程师升级至服务专家条件：status为1
            return TypeDictionary.ORDERTYPE_FIELDENGINEER_FEEDBACK.getCode().equals(escalationOrderT.getStatus());
        } else if ("4,5".contains(type) && null != escalationOrderT) {
            // 技师再次升级至服务专家条件：status为2
            return TypeDictionary.ORDERTYPE_TECHNICIAN_CONFIRMING.getCode().equals(escalationOrderT.getStatus());
        } else if ("6".equals(type) && null != escalationOrderT) {
            // 技师再次升级至服务专家条件：status为6
            return TypeDictionary.ORDERTYPE_TECHNICIAN_CONFIRMING_FROMSERVICEEXPERT.getCode().equals(escalationOrderT.getStatus());
        }
        return false;
    }

    //新增：升级单原因表
    private int insertEscalationReasonT(SubmitReasonRequest request, UserT userT, SynSfParam synSfParam) {
        EscalationReasonT escalationReasonT = new EscalationReasonT();

        escalationReasonT.setOrderId(request.getEscalationOrderId());
        if ("1".equals(request.getType())) {
            escalationReasonT.setEscalationType(TypeDictionary.ESCALATIONTYPE_TECHNICIAN_TO_FIELDENGINEER.getCode());
        } else if ("2".equals(request.getType())) {
            escalationReasonT.setEscalationType(TypeDictionary.ESCALATIONTYPE_FIELDENGINEER_TO_SERVICEEXPERT.getCode());
        } else if ("3".equals(request.getType())) {
            escalationReasonT.setEscalationType(TypeDictionary.ESCALATIONTYPE_FIELDENGINEER_TO_SERVICEEXPERT_CREAT.getCode());
        } else if ("4".equals(request.getType())) {
            escalationReasonT.setEscalationType(TypeDictionary.ESCALATIONTYPE_TECHNICIAN_TO_SERVICEEXPERT.getCode());
        } else if ("5".equals(request.getType())) {
            escalationReasonT.setEscalationType(TypeDictionary.ESCALATIONTYPE_TECHNICIAN_TO_SERVICEEXPERT_REMIND.getCode());
        } else if ("6".equals(request.getType())) {
            escalationReasonT.setEscalationType(TypeDictionary.ESCALATIONTYPE_TECHNICIAN_TO_SERVICEEXPERT_2.getCode());
        }
        escalationReasonT.setReasonKey(Integer.valueOf(request.getReasonKey()));
        escalationReasonT.setReasonValue(request.getReasonValue());
        if (null != request.getSupplementReason()) {
            escalationReasonT.setSupplementReason(request.getSupplementReason());
        }
        escalationReasonT.setFlag(0);
        escalationReasonT.setCreator(userT.getId());
        escalationReasonT.setCreateTime(LocalTimeUtil.getRealCurrentTime());

        int reasonInt = escalationReasonTDao.insertSelective(escalationReasonT);
        if (CollectionUtils.isNotEmpty(request.getSupplementInfo())) {
            if (request.getSupplementInfo().size() > 10) {
                throw new CommonException(ExceptionStatus.PARAMS_ERROR.getStatus(), ExceptionStatus.PARAMS_ERROR.getMessage());
            }
            List<SynSfSupplementParam> supplementList = new ArrayList<>();
            for (SubmitReasonRequest.SupplementInfo entity : request.getSupplementInfo()) {
                EscalationReasonSupplementT supplementT = new EscalationReasonSupplementT();
                supplementT.setEscalationReasonId(escalationReasonT.getId());
                supplementT.setOrderNo(entity.getSupplementOrderNo());
                supplementT.setPartNo(entity.getSupplementPartNo());
                supplementT.setPartName(entity.getSupplementPartName());
                supplementT.setCount(entity.getSupplementCount());
                supplementT.setCreator(UserThreadLocal.get().getId());
                supplementT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                //同步给SF-零件订单
                SynSfSupplementParam obj = new SynSfSupplementParam();
                obj.setWorkOrderNo(entity.getSupplementOrderNo());
                obj.setPartNo(entity.getSupplementPartNo());
                obj.setPartName(entity.getSupplementPartName());
                obj.setPartCount(String.valueOf(entity.getSupplementCount()));
                supplementList.add(obj);
                int i = reasonSupplementTMapper.insertSelective(supplementT);
                reasonInt = i < reasonInt ? i : reasonInt;
            }
            synSfParam.setSupplementInfoList(supplementList);
        }
        return reasonInt;
    }

    //新增：升级单表
    private long insertEscalationOrderT(SubmitReasonRequest request, UserT userT, SynSfParam synSfParam) {
        EscalationOrderT escalationOrderT = new EscalationOrderT();
        String type = request.getType();
        //Type  1：技师创建工单；3：区域工程师创建工单
        escalationOrderT.setWorkOrderId(request.getWorkOrderId());
        /**
         * <p>
         *     自动生成工单编号，由 redis 更改为 sqlServer
         * </p>
         */
        //String escalationOrderNo = getEscalationOrderNo();
        String escalationOrderNo = OrderGenerateUtil.getEscalationOrderNo();
        escalationOrderT.setOrderNo(escalationOrderNo);
        synSfParam.setUpgradeAppNo(escalationOrderNo);
        String createTime = LocalTimeUtil.getRealCurrentTime();
        if ("1".equals(type)) {
            escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_FIELDENGINEER_FEEDBACK.getCode());
            //表单提交人角色
            synSfParam.setUpgradeSubmitUser(RoleType.SERVICE_TECHNICIAN.getMessage());
        } else if ("3".equals(type)) {
            escalationOrderT.setStatus(TypeDictionary.ORDERTYPE_SERVICEEXPERT_FEEDBACK.getCode());
            //表单提交人角色
            synSfParam.setUpgradeSubmitUser(RoleType.REGIONAL_ENGINEER.getMessage());
        }
        //升级工单申请时间
        synSfParam.setUpgradeCreatedDateTime(createTime);
        escalationOrderT.setFlag(0);
        escalationOrderT.setCreator(userT.getId());
        escalationOrderT.setCreateTime(createTime);
        escalationOrderTDao.insertSelective(escalationOrderT);
//        if ("3".equals(type)) {
//            synSfParam.setEngineerUpgradeDateTime(createTime);
//            List<UserT> expertList = escalationNotifyService.getReasonTypeExpert(escalationOrderT.getId());
//            if (expertList != null && expertList.size() > 0) {
//                synSfParam.setServiceExpertName(expertList.get(0).getContact());
//                synSfParam.setServiceExpertPhone(expertList.get(0).getPhone());
//            }
//        }
//        if ("1".equals(type)) {
//            List<UserT> engineersList = escalationNotifyService.getEngineers(escalationOrderT.getId());
//            if (engineersList != null && engineersList.size() > 0) {
//                synSfParam.setEngineerPhone(engineersList.get(0).getContact());
//                synSfParam.setEngineerName(engineersList.get(0).getPhone());
//            }
//        }
        return escalationOrderT.getId();
    }

    //新增：流水表
    public int insertEscalationFlowT(Long orderId, Integer flowType, Integer orderStatus, UserT userT,String expertsUserName) {
        EscalationFlowT escalationFlowT = new EscalationFlowT();
        escalationFlowT.setOrderId(orderId);
        escalationFlowT.setUserId(userT.getId());
        escalationFlowT.setType(flowType);
        escalationFlowT.setOrderStatus(orderStatus);
        escalationFlowT.setFlag(0);
        escalationFlowT.setCreator(userT.getId());
        escalationFlowT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
        escalationFlowT.setExpertsUserName(expertsUserName);
        String comment1 = "发起升级任务";
        String comment2 = "寻求服务专家支持";
        String comment3 = "已填写解决方案";
        String comment4 = "升级到服务专家";
        String comment5 = "升级完成";
        String comment6 = "服务工单异常关闭，升级任务结束";
        String comment7 = "服务工单已取消，升级任务结束";
        String comment8 = "服务工单已完成，升级任务结束";
        String comment9 = "技师拒绝服务专家反馈，继续寻求服务专家支持";
        String comment10 = "服务工单已完成，升级任务完成";    // 和8的区别：8是未提供反馈解决方案的升级工单，10是提供反馈解决方案的升级工单

        switch (orderStatus) {
            case 1:
                switch (flowType) {
                    case 1:
                        escalationFlowT.setComments(comment1);
                        break;
                    case 6:
                        escalationFlowT.setComments(comment2);
                        break;
                }
                break;
            case 2:
                switch (flowType) {
                    case 6:
                        escalationFlowT.setComments(comment2);
                        break;
                    case 7:
                        escalationFlowT.setComments(comment3);
                        break;
                }
                break;
            case 3:
                switch (flowType) {
                    case 2:
                        escalationFlowT.setComments(comment4);
                        break;
                    case 3:
                        escalationFlowT.setComments(comment1);
                        break;
                    case 4:
                        escalationFlowT.setComments(comment4);
                        break;
                    case 5:
                        escalationFlowT.setComments(comment2);
                        break;
                    case 6:
                        escalationFlowT.setComments(comment9);
                        break;
                }
                break;
            case 4:
                switch (flowType) {
                    case 6:
                        escalationFlowT.setComments(comment2);
                        break;
                    case 8:
                        escalationFlowT.setComments(comment3);
                        break;
                    // 9: 确认来自区域工程师的反馈；13：确认来自服务专家的反馈
                    case 9:
                    case 13:
                        escalationFlowT.setComments(comment5);
                        break;
                    case 14:
                        escalationFlowT.setComments(comment10);
                }
                break;
            case 5:
                switch (flowType) {
                    case 10:
                        escalationFlowT.setComments(comment6);
                        break;
                    case 11:
                        escalationFlowT.setComments(comment7);
                        break;
                    case 12:
                        escalationFlowT.setComments(comment8);
                        break;
                }
                break;

            case 6:
                switch (flowType) {
                    case 8:
                        escalationFlowT.setComments(comment3);
                        break;
                }
                break;
        }
        return escalationFlowTDao.insertSelective(escalationFlowT);
    }

    /**
     * 获取升级工单编号
     *
     * @return
     */
    private String getEscalationOrderNo() {
        return SerialNumberUtil.getSerialNumber("EO");
    }


    private int isPrincipalExisted(String type, String reasonKey, UserT userT, Long orderId) {
        //Type  1：技师创建工单；2：工程师升级工单；3：区域工程师创建工单；4：技师再升级; 5 催单升级; 6 技师继续升级（不同意专家反馈）
        if (type.equals("1")) {
            //当前user为技师
            userT = workOrderTDao.getFieldEngineerByWorkOrderId(orderId);
            if (null == userT) {
                return -1;
            }
        } else {
            if (type.equals("6")) {
                EscalationOrderT escalationOrderT = escalationOrderTDao.selectByPrimaryKey(orderId);
                userT = workOrderTDao.getFieldEngineerByWorkOrderId(escalationOrderT.getWorkOrderId());
                if (null == userT) {
                    return -1;
                }
            }
            // 当前user为区域工程师
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("type", type);
            paramsMap.put("reasonKey", reasonKey);
            paramsMap.put("principalPhone", userT.getPhone());
            List<UserT> userTS = positionExpertTDao.selectPositionExpertByTypeAndReasonKey(paramsMap);
            if (userTS.size() == 0) {
                return -2;
            }
        }
        return 0;
    }
}
